package traveldreampm.web;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import traveldreampm.ejb.dtos.UtenteDTO;
import traveldreampm.ejb.manager.GestoreUtentiLocal;

@ManagedBean
@ViewScoped
public class AutenticazioneBean {

	@EJB
	GestoreUtentiLocal gestoreUtenti;

	private UtenteDTO utenteDTO;

	public AutenticazioneBean() {
	}

	@PostConstruct
	public void init() {
		this.reloadUtenteDTO();
	}

	public UtenteDTO getUtenteDTO() {
		return utenteDTO;
	}

	public void setUtenteDTO(UtenteDTO utenteDTO) {
		this.utenteDTO = utenteDTO;
	}

	public void reloadUtenteDTO() {
		this.setUtenteDTO(gestoreUtenti.getCurrentUserDTO());
	}

	public void login(String mail, String password) throws ServletException {
		// Effettuo il login
		HttpServletRequest request = (HttpServletRequest) FacesContext
				.getCurrentInstance().getExternalContext().getRequest();
	
		request.login(mail, password);
		
		// Ricarico i dati utente
		this.reloadUtenteDTO();
	}

	public String logout() {
		FacesContext.getCurrentInstance().getExternalContext()
				.invalidateSession();
		
		this.setUtenteDTO(null);
		
		return "/index?faces-redirect=true";
	}

	public String getUserProfileString() {
		return this.getUtenteDTO().getNome() + " "
				+ this.getUtenteDTO().getCognome();
	}

	public boolean isCurrentUserImpiegato() {
		return this.getUtenteDTO().getIsImpiegato();
	}

}
